package cn.alpha.intell.rbtlib.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;

/**
 * 播放音频url
 * @author white
 * @date 16/8/1
 */
public class MediaPlayUtil {

    private static final String TAG = "MediaPlayUtil";
    private static MediaPlayer sMediaPlayer;
    private static Context media_context;
    private static String media_url;
    private static MediaPlayCallback mediaCallback;
    private static boolean bufferingPause=false;
    public static void playAndNext(final Context context, final String[] urls, final int curIndex, final MediaPlayCallback callback) {
        if(urls == null || curIndex >= urls.length || TextUtils.isEmpty(urls[curIndex])){
            if(callback!=null) {
                callback.onFinish();
            }
            return;
        }
        try {
            // 因为是static,防止资源未release导致不能播放
            stopAll();
            Uri uri = Uri.parse(urls[curIndex]);
            sMediaPlayer = new MediaPlayer();
            sMediaPlayer.reset();
            sMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            sMediaPlayer.setDataSource(context, uri);
//            sMediaPlayer.setDataSource(urls[curIndex]);
            sMediaPlayer.prepareAsync();
            sMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    LogTool.d(TAG, "setOnPreparedListener "+mp);
                    if(mp != null){
                        mp.start();
                    }
                    if(callback!=null) {
                        callback.onStart();
                    }
                }
            });
            sMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    LogTool.d(TAG, "setOnCompletionListener " + mp.isPlaying());
                    stopAll();
                    int next = curIndex + 1;
                    playAndNext(context, urls, next, callback);
                }
            });
            sMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    LogTool.d(TAG, "onError what:" + what + "extra:" + extra);
                    stopAll();
                    if(callback!=null) {
                        callback.onFinish();
                    }
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            if(callback != null) {
                callback.onFinish();
            }
        }
    }

    public static void pause(){
        if (sMediaPlayer != null ){
            if(sMediaPlayer.isPlaying()) {
                sMediaPlayer.pause();
                bufferingPause=false;
            }
            else{
                sMediaPlayer.reset();
                bufferingPause=true;
            }

        }

    }
    public static void start(){
        if (sMediaPlayer != null )
            if(bufferingPause){
                play(media_context,media_url,mediaCallback);
            }else{
                sMediaPlayer.start();
            }
        bufferingPause=false;
    }
    public static void playQueue(final Context context, final String[] urls, final MediaPlayCallback callback){
        if(urls == null || urls.length == 0){
            if(callback != null) {
                callback.onFinish();
            }
            return;
        }
        for (String url : urls){
            LogTool.d(TAG, "url:"+url);
        }
        playAndNext(context, urls, 0, callback);
    }

    public static void play(final Context context, String url, final MediaPlayCallback callback){
        media_context=context;
        media_url=url;
        mediaCallback=callback;
        if(context == null || TextUtils.isEmpty(url)){
            if(callback!=null) {
                callback.onFinish();
            }
            return;
        }
        playAndNext(context, new String[]{url}, 0, callback);
    }


    public static void stopAll(){
        try{
            if (sMediaPlayer != null && sMediaPlayer.isPlaying()) {
                sMediaPlayer.pause();
                sMediaPlayer.stop();
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (sMediaPlayer != null) {
                    sMediaPlayer.release();
                    sMediaPlayer = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //返回当前Media播放的位置
    public static int getCurrentPos(){
        return  sMediaPlayer.getCurrentPosition();
    }

    //返回当前Media的总时长
    public static int getMediaDuration(){
        try {
        if (sMediaPlayer != null &&sMediaPlayer.isPlaying())
            return sMediaPlayer.getDuration();
        }
        catch (IllegalStateException e){
            sMediaPlayer=null;
            sMediaPlayer=new MediaPlayer();
            play(media_context,media_url,mediaCallback);
        }
        return Integer.MAX_VALUE;
    }

    public static boolean isPlaying(){
        if(sMediaPlayer!=null)
            try {
                return sMediaPlayer.isPlaying();

            }
            catch (IllegalStateException e){
                return false;
            }
        else
            return false;
    }

    public static void setMediaPlayPos(int pos){
        try {
            if (sMediaPlayer != null && sMediaPlayer.isPlaying())
                sMediaPlayer.seekTo(pos);

        }catch (IllegalStateException e){
            LogTool.e(TAG,e.toString());
        }
    }


    /***
     * generate uri from resource ID class
     */
    public static class MediaUrlParser{

        /**
         * generate Uri as String from resource id
         * @param context
         * @param resId
         * @return
         */
        public static String from(Context context, int resId) {
            return "android.resource://"+ context.getPackageName() + "/" + resId;
        }

        /**
         * generate Uri as String from resource filename
         * @param context
         * @param rawfileName  raw/filename （不要文件后缀)
         * @return
         */
        public static String from(Context context,String rawfileName){
            return "android.resource://"+ context.getPackageName() + "/" + rawfileName;
        }


    }

    /**
     * 回调接口
     */
    public interface MediaPlayCallback {
        void onFinish();
        void onStart();
    }
}
